package io.renren.modules.generator.controller;



import java.io.File;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import io.lettuce.core.dynamic.annotation.Param;
import io.renren.common.utils.FileExcel;
import io.renren.common.utils.FileUpload;
import io.renren.common.utils.ImportExcelUtil;
import io.renren.modules.generator.entity.TTrainingCheckEntity;
import io.renren.modules.generator.entity.TTrainingEntity;
import io.renren.modules.generator.entity.TTrainingObjectEntity;
import io.renren.modules.generator.entity.vo.TTrainingScoreVo;
import io.renren.modules.generator.service.TTrainingCheckService;
import io.renren.modules.generator.service.TTrainingObjectService;
import io.renren.modules.generator.service.TTrainingService;
import io.renren.modules.user.entity.TPeopleEntity;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.io.FileUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import io.renren.modules.generator.entity.TTrainingScoreEntity;
import io.renren.modules.generator.service.TTrainingScoreService;
import io.renren.common.utils.R;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;


/**
 * 考核成绩表
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2019-08-07 13:58:41
 */
@RestController
@RequestMapping("/ttrainingscore")
public class TTrainingScoreController {
    @Autowired
    private TTrainingScoreService tTrainingScoreService;

    @Autowired
    private TTrainingService tTrainingService;
    /**
     * 列表
     */
    @RequestMapping("/list")
    //@RequiresPermissions("generator:ttrainingscore:list")
    public R list(@RequestParam Map<String, Object> params){
        List list=tTrainingScoreService.list(new QueryWrapper<TTrainingScoreEntity>().eq("id",1));
        return R.ok().put("list", list);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("generator:ttrainingscore:info")
    public R info(@PathVariable("id") Integer id){
		TTrainingScoreEntity tTrainingScore = tTrainingScoreService.getById(id);

        return R.ok().put("tTrainingScore", tTrainingScore);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("generator:ttrainingscore:save")
    public R save(@RequestBody TTrainingScoreEntity tTrainingScore){
		tTrainingScoreService.save(tTrainingScore);

        return R.ok();
    }

    /**
     * 批量修改 成绩
     */
    @RequestMapping("/update")
    //@RequiresPermissions("generator:ttrainingscore:update")
    public R update(@RequestBody TTrainingScoreEntity tTrainingScore){
        tTrainingScoreService.updateBatchById(tTrainingScore.getLit());  //修改成绩
        Double num=tTrainingScoreService.getHgl(tTrainingScore);      //根据成绩 计算合格率
        TTrainingEntity tTraining=new TTrainingEntity();
        tTraining.setId(tTrainingScore.getTrainingId());
        tTraining.setQualificationrate(num);
        tTrainingService.updateQualificationrate(tTraining);    //往训练里 修改合格率
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("generator:ttrainingscore:delete")
    public R delete(@RequestBody Integer[] ids){
		tTrainingScoreService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }


    /**
     * 历史 成绩查看
     */
    @RequestMapping("/getTTrainingScore")
    @ResponseBody
    //@RequiresPermissions("generator:ttrainingscore:getTTrainingScore")
    public R getTTrainingScore(@RequestBody TTrainingScoreEntity tTrainingScore){
        List<TTrainingScoreEntity> list=tTrainingScoreService.getTTrainingScore(tTrainingScore);
        return R.ok().put("list", list);
    }
    /**
     * 最新成绩查看
     */
    @RequestMapping("/selectList")
    @ResponseBody
   // @RequiresPermissions("generator:ttrainingscore:selectList")
    public R selectList(@RequestBody TTrainingScoreEntity tTrainingScore){
        List<TTrainingScoreEntity> list=tTrainingScoreService.selectList(tTrainingScore);
        List<Map<String,Object>> decidelist=tTrainingScoreService.decideList();
        return R.ok().put("list", list).put("decidelist",decidelist);
    }

    /**
     * 倒入
     */
    int objectId=0; //科目id
    int TrainingCheckId=0; //考核信息id
    int peopleid=0;  //人员id
    List<TTrainingScoreVo> list;  //数据
    @RequestMapping("/asd")
    @ResponseBody
    //@RequiresPermissions("generator:ttrainingscore:asd")
    public R imputTestdd(HttpServletRequest request,@RequestParam("file")MultipartFile file){
        String fileF=null;   //后缀
        String numName=new Date().getTime() + "_" + new Random().nextInt(1000);    //自动生成文件名字
            String fileName = file.getOriginalFilename();//通过上传的文件得到他的后缀。
            if (fileName != null && fileName != "") {
                fileF = fileName.substring(fileName.lastIndexOf("."), fileName.length());//文件后缀
            }
        //动态生成文件
        Date date = new Date();
        String sdf=new SimpleDateFormat("yyyy-MM-dd").format(date);    //自动生成日期文件
        String names=sdf+File.separator+numName+fileF;
        FileExcel.updateFile(file,numName,sdf);
        String strUrl=sdf+File.separator+numName+fileF;
        ImportExcelUtil importExcelUtil=new ImportExcelUtil();
        String id=request.getParameter("trainingId");
        Integer trainingId = Integer.parseInt(id);
        //excel 导入数据demo
        String URL="/usr/local/fireFileExcal/"+strUrl;     //服务器地址
        File url = new File(URL);
        List<List<Object>> dataList= null;
        list=new ArrayList<>();
        try {
            dataList = importExcelUtil.importExcel(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //数据封装格式一，将表格中的数据遍历取出后封装进对象放进List
        Object type_name=null;  //科目名称
        Object type_id=null; //身份证号
        Object score=null;   //成绩
        //Object trainingId=trainingScoreEntity.getTrainingId(); //训练id
        for (int a=0;a<dataList.get(1).size()-3;a++){
                for (int i = 1; i <dataList.size(); i++) {
                         type_name = dataList.get(1).get(a+3);   //科目名称
                        TTrainingObjectEntity obj=new TTrainingObjectEntity();
                         obj.setObjectName((String)type_name);
                         obj.setTiainingId(trainingId);
                         Object name=dataList.get(i).get(1);
                         type_id=(dataList.get(i).get(2));
                             TPeopleEntity pele = new TPeopleEntity();
                             pele.setIdcard((String) dataList.get(i).get(2));
                             getPeople(pele);
                          getKmId(obj);
                         //type_id = dataList.get(i).get(1);        //身份证号
                         score = dataList.get(i).get(a+3);        //成绩

                        if(i<=1){

                        }else{
                            TTrainingScoreVo signupCategory=new TTrainingScoreVo();
                            signupCategory.setName((String) name);
                            signupCategory.setTrainingIdName((String)type_name);
                            signupCategory.setTrainingPeopleId(peopleid);
                            signupCategory.setScore((String)score);
                            signupCategory.setTrainingObjectId(objectId);
                            signupCategory.setTrainingId((Integer)trainingId);
                            signupCategory.setTrainingCheckId(TrainingCheckId);
                            list.add(signupCategory);
                        }

                    System.out.println("------------------");
                    System.out.println((String)type_id+":"+(String)type_name);
                }
        }
//        tTrainingScoreService.DrTTrainingScore(list);
//        System.out.println(list.size());
        return R.ok().put("list",list);
    }

    /**
     * 导入 保存
     */
    @RequestMapping("/bc")
    public R selectList(){
        if(list==null){
            String l="请先选择Excil";
            return R.ok().put("l",l);
        }else{
            tTrainingScoreService.DrTTrainingScore(list);
        }
        return R.ok();
    }
    @Autowired
    private TTrainingObjectService trainingObjectService;
    @Autowired
    private TTrainingCheckService tTrainingCheckService;
    /**
     * 获取id
     * @return
     */
    public R getKmId(TTrainingObjectEntity obj){
        TTrainingObjectEntity s=trainingObjectService.getKmid(obj);
        TTrainingCheckEntity s1=tTrainingCheckService.getNewInfo();
        if(s==null){}else{ System.out.println(s.getObjectId());objectId=s.getObjectId();}
       if(s1==null){}else{System.out.println(s1.getId());TrainingCheckId=s1.getId()+1;}
        return R.ok();
    }

    /**
     * 获取id
     * @return
     */
    public R getPeople(TPeopleEntity peopleEntity){
        TPeopleEntity p=tTrainingScoreService.getPeopleId(peopleEntity);
        if(p==null){
            return R.ok();
        }
        System.out.println(p.getId());
        peopleid=p.getId();
        return R.ok();
    }
    /**
     * 自动评分
     */
    @RequestMapping("/automaticScoring")
    @RequiresPermissions("generator:ttrainingscore:automaticScoring")
    public R automaticScoring(@RequestBody TTrainingScoreEntity tTrainingScore){
        List<TTrainingScoreEntity> list=tTrainingScoreService.automaticScoring(tTrainingScore);
        return R.ok().put("list", list);
    }

//    /**
//     * 修改
//     */
//    @RequestMapping("/updatePlScore")
//    //@RequiresPermissions("generator:ttrainingscore:updatePlScore")
//    public R updatePlScore(@RequestBody TTrainingScoreEntity tTrainingScore){
//        tTrainingScoreService.updatePlScore(tTrainingScore.getList());
//        return R.ok();
//    }
}
